#pragma once

#include "Common.h"

#include <array>
#include <atomic>
#include <cstddef>
#include <mutex>

namespace mp {

class CentralCache {
  public:
    static CentralCache &getInstance() {
        static CentralCache instance;
        return instance;
    }

    void *fetchRange(size_t idx, size_t batchNum);
    void returnRange(void *start, size_t size, size_t bytes);

  private:
    CentralCache() {
        for (auto &ptr : centralFreeList_) {
            ptr.store(nullptr, std::memory_order_relaxed);
        }

        for (auto &lock : locks_) {  // 初始化所有锁
            lock.clear();
        }
    }

    void *fetchFromPageCache(size_t size);  // 从页缓存获取内存

  private:
    std::array<std::atomic<void *>, FREE_LIST_SIZE> centralFreeList_;  // CentralCache 的自由链表
    std::array<std::atomic_flag, FREE_LIST_SIZE> locks_;               // 用于同步的自旋锁
};

}  // namespace MemoryPool